package avicit.im.common.util;

import javax.tools.JavaCompiler;
import javax.tools.ToolProvider;
import java.io.File;
import java.io.FileWriter;
import java.io.PrintWriter;
import java.lang.reflect.Constructor;
import java.lang.reflect.Method;
import java.net.URL;
import java.net.URLClassLoader;

/**
 * @author Administrator
 *	
 */
public class DynamicExeMain {
	
	@SuppressWarnings({ "unchecked", "rawtypes" })
	public static Object eval(String str) throws Exception{
		//生成java文件
		//转换方法名名为带类名称的
		String fStr = str.replaceAll("cf_", "FuntionJava.cf_");
		fStr =fStr.replaceAll("'", "\\\"");
		fStr =fStr.replaceAll("\"", "\\\"");
		
		StringBuffer sbSql = new StringBuffer();
		sbSql.append("package avicit.im.common.util; \n");
		sbSql.append("public class DynamicExeJava { \n");
		sbSql.append("	public Object eval(){ \n");
		sbSql.append("    Object  obj=  "+fStr+"; \n");
		sbSql.append("    return obj; \n");
		sbSql.append("  } \n");
		sbSql.append("} \n");
		//写入java文件中
		String classPath = DynamicExeMain.class.getResource("/").getPath(); //得到classpath
		File f = new File(classPath+"/avicit/im/common/util/DynamicExeJava.java");
		PrintWriter pw = new PrintWriter(new FileWriter(f));
		pw.println(sbSql.toString());
		pw.close();
		//编译文件
		JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
	    int result = compiler.run(null,null,null,new String[]{classPath+"/avicit/im/common/util/FuntionJava.java",classPath+"/avicit/im/common/util/DynamicExeJava.java"});
	    if(result==0){
	    	System.out.println("编译成功");
	    	
	    	Class clz = null;
	        // 使用URLClassLoader加载class到内存
            URL[] urls = new URL[] { new URL("file:" + classPath + "/") };
            URLClassLoader cLoader = new URLClassLoader(urls);
            clz = cLoader.loadClass("avicit.im.common.util.DynamicExeJava");
			Constructor appleConstructor = clz.getConstructor();
	        Object appleObj = appleConstructor.newInstance();
	        Method getPriceMethod = clz.getMethod("eval");
	        return getPriceMethod.invoke(appleObj);
	    }else{
	    	 System.out.println("编译失败");
	    }
	    return null;
	}
	
	public static void main(String[] args) {
		try {
			Object obj = DynamicExeMain.eval(" cf_upper( cf_trim( 'CTG.00' ) ) +'_'+ '2013' +'_'+ cf_If( cf_len( '关于开展企业文化理念宣贯活动的通知' )>5 , cf_substring( '关于开展企业文化理念宣贯活动的通知' ,0,5) , '关于开展企业文化理念宣贯活动的通知' ) ");
			System.out.println(obj.toString());
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}
